import axios,{ AxiosInstance, AxiosRequestConfig, AxiosResponse} from 'axios'

const ins: AxiosInstance = axios.create({
    baseURL:'http://121.89.205.189:3001/admin',
    timeout:6000
    // timeout: 50000
})

ins.interceptors.request.use((config: AxiosRequestConfig) =>{
    config.headers.common['token'] = ''
    return config
}, error=> Promise.reject(error)) 

ins.interceptors.response.use((res:AxiosResponse)=>{
    return res.data
},error=>Promise.reject(error))

export default function request(config:AxiosRequestConfig): Promise<AxiosResponse<any>>{
    const { url='',method='GET',data={},headers='' } = config
    switch (method.toUpperCase()) {
        case 'GET':
            return ins.get(url,{params:data})
        case 'POST':
            if(headers['content-type'] === 'application/x-www-form-url-encoded'){
                const p = new URLSearchParams()
                for(let key in data){
                    p.append(key,data[key])
                }
                return ins.post(url, p, {headers})
            }
            if(headers['content-type'] === 'mutipart/form-data') {
                const p = new FormData()
                for(let key in data){
                    p.append(key,data[key])
                }
                return ins.post(url,p,{headers})
            }
            //默认applicatio/json
            return ins.post(url,data)
        case 'PUT':
            return ins.put(url, data)
        case 'DELECT':
            return ins.delete(url,data)
        case 'PATCH':
            return ins.patch(url,data)
        default:
            return ins(config)
    }
}